﻿using HZH_Controls.Controls;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 渐变.admin_Form
{
    public partial class admin_userManager : Form
    {
        public admin_userManager()
        {
            InitializeComponent();
        }

        private void admin_userManager_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;
            loadNotice();
            var countsql = new StringBuilder();
            countsql.Append($"Select COUNT(*)");
            countsql.Append(Environment.NewLine);
            countsql.Append($"From uUser");

            int count = (int)DBHelper.ExecuteScalar(countsql.ToString());

            var ds = new List<object>();
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    ds.Add(i);
                }
            }
            this.pc1.DataSource = ds;
            this.pc1.PageSize = 10;
            this.pc1.StartIndex = 0;
            this.pc1.FirstPage();
            this.pc1.PageCount = count / 10 + (count % 10 > 0 ? 1 : 0);
            this.pc1.ShowSourceChanged += pc1_ShowSourceChanged;

            var sql = new StringBuilder();
            sql.Append($"Select top 10 *");
            sql.Append(Environment.NewLine);
            sql.Append($"from (select row_number() over(order by uId asc) as rownumber,* From uUser) temp");
            sql.Append(Environment.NewLine);
            sql.Append($"WHERE rownumber > 0;");

            dt = DBHelper.ExecuteQuery(sql.ToString());
            this.userdata.DataSource = dt;
            this.userdata.First();

        }
        DataTable dt = new DataTable();
        public void loadNotice()
        {
            List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "uId", HeadText = "编号", Width = 30, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "uUsername", HeadText = "姓名", Width = 30, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "uPassword", HeadText = "密码", Width = 30, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "uPhone", HeadText = "手机号", Width = 30, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "uAddress", HeadText = "家庭地址", Width = 50, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "umoney", HeadText = "所剩余额", Width = 50, WidthType = SizeType.AutoSize });

            this.userdata.Columns = lstCulumns;
            this.userdata.IsShowCheckBox = true;
            List<object> lstSource = new List<object>();
            /*string sql = "select * from uUser";
           
            //DataTable dt = DBHelper.ExecuteQuery(sql);
            *//*ModelHandler<model.notice> mconvert = new common.ModelHandler<model.notice>();
            var list = mconvert.FillModel(dt);

            this.noticedata.DataSource = list;*//*

            dt = DBHelper.ExecuteQuery(sql);
            this.userdata.DataSource = dt;
            this.userdata.First();*/
        }


        /*分页控件下一页的事件    start*/
        private void pc1_ShowSourceChanged(object currentSource)
        {
            var list = this.pc1.GetCurrentSource();
            if (list != null && list.Count > 0)
            {
                var sql = new StringBuilder();
                sql.Append($"Select top 10 *");
                sql.Append(Environment.NewLine);
                sql.Append($"from (select row_number() over(order by uId asc) as rownumber,* From uUser) temp");
                sql.Append(Environment.NewLine);
                sql.Append($"WHERE rownumber > {10 * ((int)list[0] / 10)};");

                DataTable dt = new DataTable();
                dt = DBHelper.ExecuteQuery(sql.ToString());
                loadNotice();
                this.userdata.DataSource = dt;
            }
            else
            {
                this.userdata.DataSource = null;
            }
        }
        /*分页控件下一页的事件    end*/


        /// <summary>
        /// 导出报表为Csv
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="strFilePath">物理路径</param>
        /// <param name="tableheader">表头</param>
        /// <param name="columname">字段标题,逗号分隔</param>
        public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
        {

            try
            {
                string strBufferLine = "";
                StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
                strmWriterObj.WriteLine(tableheader);
                strmWriterObj.WriteLine(columname);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strBufferLine = "";
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j > 0)
                            strBufferLine += ",";
                        strBufferLine += dt.Rows[i][j].ToString();
                    }
                    strmWriterObj.WriteLine(strBufferLine);
                }
                strmWriterObj.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
       

        /*用户添加按钮    start*/
        private void btnAdd_Click(object sender, EventArgs e)
        {
            addUserForm userForm = new addUserForm();
            DialogResult dir = userForm.ShowDialog();
            /* rentCarForm.Show();*/
            if (dir == DialogResult.OK)
            {      
                admin_userManager_Load(null, null);
            }     
        }
        /*用户添加按钮    end*/


        /*用户删除按钮 批量删除   start*/
        #region
        private void btnDelete_Click(object sender, EventArgs e)
        {
            //string id = (userdata.SelectRow.DataSource as DataRow)["uId"].ToString();
            if (userdata.SelectRows != null && userdata.SelectRows.Count > 0)
            {
                var uids = new List<int>();
                foreach (var item in userdata.SelectRows)
                {
                    var tempid = Convert.ToInt32((item.DataSource as DataRow)["uId"]);
                    uids.Add(tempid);
                }
                DialogResult dir = MessageBox.Show("您确定要删除该用户吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dir == DialogResult.OK)
                {
                    var uidsstr = new StringBuilder();
                    uidsstr.Append("(");
                    foreach (var item in uids)
                    {
                        uidsstr.Append($"{item},");
                    }
                    uidsstr.Remove(uidsstr.Length - 1, 1);
                    uidsstr.Append(")");
                    string sql = $"delete from uUser where uId IN {uidsstr};";
                    int result = DBHelper.ExecuteNonQuery(sql);
                    if (result > 0)
                    {
                        this.ShowSuccessTip("删除成功！");
                        admin_userManager_Load(null, null);
                    }
                    else
                    {
                        this.ShowErrorTip("删除失败！");
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                this.ShowErrorTip("未选择任何用户，请选择要删除的用户再进行删除!");
            }

        }
        #endregion
        /*用户删除按钮    end*/


        /*用户修改按钮    start*/
        private void btnEdit_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32((userdata.SelectRow.DataSource as DataRow)["uId"]);
            string uUsername = (userdata.SelectRow.DataSource as DataRow)["uUsername"].ToString();
            string uPassword = (userdata.SelectRow.DataSource as DataRow)["uPassword"].ToString();
            string uPhone = (userdata.SelectRow.DataSource as DataRow)["uPhone"].ToString();
            string uAddress = (userdata.SelectRow.DataSource as DataRow)["uAddress"].ToString();
            string umoney = (userdata.SelectRow.DataSource as DataRow)["umoney"].ToString();
            editUserForm editUser = new editUserForm(new userInfo()
            {
                uAddress = uAddress,
                uId = id,
                umoney = umoney,
                uPassword = uPassword,
                uPhone = uPhone,
                uUsername = uUsername

            });
            DialogResult dir = editUser.ShowDialog();
            /* rentCarForm.Show();*/
            if (dir == DialogResult.OK)
            {
                //loadMsg();
                admin_userManager_Load(null, null);


            }
            //editUser.ShowDialog();
        }
        /*用户删除按钮    end*/

        private void userdata_ItemClick(object sender, DataGridViewEventArgs e)
        {
            var rows = userdata.SelectRows;
            if (rows != null && rows.Count > 0)
            {
                btnEdit.Enabled = true;
            }
            else
            {
                btnEdit.Enabled = false;
            }
           
        }

        /*导出按钮 start*/
        private void daochu_Click(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
            if (dt2csv(dt, path, "用户信息", "编号,用户名,密码,电话,地址,所剩余额"))
            {
                MessageBox.Show("导出成功,文件位置:" + path);
            }
            else
            {
                MessageBox.Show("导出失败");
            }
        }
        /*导出按钮 end*/

        private void delete_Click(object sender, EventArgs e)
        {
            if (userdata.SelectRows != null && userdata.SelectRows.Count > 0)
            {
                var uids = new List<int>();
                foreach (var item in userdata.SelectRows)
                {
                    var tempid = Convert.ToInt32((item.DataSource as DataRow)["uId"]);
                    uids.Add(tempid);
                }
                DialogResult dir = MessageBox.Show("您确定要删除该用户吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dir == DialogResult.OK)
                {
                    var uidsstr = new StringBuilder();
                    uidsstr.Append("(");
                    foreach (var item in uids)
                    {
                        uidsstr.Append($"{item},");
                    }
                    uidsstr.Remove(uidsstr.Length - 1, 1);
                    uidsstr.Append(")");
                    string sql = $"delete from uUser where uId IN {uidsstr};";
                    int result = DBHelper.ExecuteNonQuery(sql);
                    if (result > 0)
                    {
                        this.ShowSuccessTip("删除成功！");
                        admin_userManager_Load(null, null);
                    }
                    else
                    {
                        this.ShowErrorTip("删除失败！");
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                this.ShowErrorTip("未选择任何用户，请选择要删除的用户再进行删除!");
            }
        }
    }
}
